package com.wangshuqi.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("GBK");

        // 得到会话session
        HttpSession session = req.getSession();
        // 给session中存入东西
        session.setAttribute("username", "Tom");

        // 设置session存活时间为30秒
//        session.setMaxInactiveInterval(30);
        System.out.println(session.getMaxInactiveInterval()); //
        // 判断session是不是新创建的
        if (session.isNew()) {
            resp.getWriter().write("session创建成功，sessionID:" + session.getId());
        } else {
            resp.getWriter().write("已有session，sessionID:" + session.getId());
            session.invalidate(); // 销毁当前会话session，日常不建议使用
        }

        //Session创建的时候做了什么事情；
        // 1. Cookie cookie = new Cookie("JSESSIONID",sessionId);
        // 2. resp.addCookie(cookie);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
